package com.han.jdbc.mysql.commons_dbcp;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.han.jdbc.mysql.uils.JDBCUtils;


/**
* @author hanpeng
* @version 创建时间：2020年7月6日 上午11:53:36
* @ClassName 类名称
* @Description 类描述
*/
public class BasicDataSourceExample {
	public final Logger logger = LoggerFactory.getLogger(BasicDataSourceExample.class);
	@Test
	public void name() {
		BasicDataSourceExample basicDataSourceExample = new BasicDataSourceExample();
		Logger logger2 = basicDataSourceExample.logger;
		
		System.out.println(logger2);
	}
	
	@Test
	public void testBasicDataSource() {
		try {
			setupDataSource();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static DataSource setupDataSource() throws Exception {
		InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("dbcp.properties");
		Properties pros = new Properties();
		pros.load(is);
		BasicDataSource ds = BasicDataSourceFactory.createDataSource(pros);
		Connection connection = ds.getConnection();
		//connection.close();
		//ds.close();
		String sql = "UPDATE `order` SET order_name=?";
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			//1.获取数据库的连接
			conn = ds.getConnection();
			//2.预编译sql语句，返回PreparedStatement的实例
			ps = conn.prepareStatement(sql);
			//3.填充占位符
			ps.setObject(1, "han");// 小心参数声明错误！！
			//4.执行
			//查询的话返回true，默认时匹配的行数 useAffectedRows=true 是更新的行数
			int num = ps.executeUpdate();
			
			System.out.println(num);
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//5.资源的关闭
			JDBCUtils.closeResource(conn, ps);
			
		}
		
		
		return ds;
	}

	public static void shutdownDataSource(DataSource ds) throws SQLException {
		BasicDataSource bds = (BasicDataSource) ds;
		//关闭连接池中所有的空闲连接 但是被拿走的连接则不受影响  connection.close() 方法也不会返回连接池 而是被真正关闭
		//此方法调用后  如果再调用  getConnection() 抛出异常
		//bds.close();调用时幂等的 多次调用没有作用
		bds.close();
	}
}
